#!/usr/bin/env python3
# encoding=utf-8


import datetime

from flask_jwt_extended import create_access_token
import arrow

from app.db.models.users import Role, Token, User
from app.db.models.packages import Packages


class InitData(object):

    def __init__(self):
        if self.is_exists_data():
            print("已经完成初始， 不能重复执行")
            exit()

    @staticmethod
    def is_exists_data():
        if Role.objects.filter(name="普通用户").first():
            return True
        return False

    def init_role(self):
        for item in [("普通用户", True), ("管理员", False)]:
            Role(name=item[0], isDefaultRole=item[1], permissions=[]).save()

    def init_package(self):
        pkg_list = [
            {
                "create_time": arrow.utcnow().datetime,
                "key": "scanv_free",
                "name": "免费版",
                "marks": "免费版",
                "operator": "scanv",
                "is_default_plan": True,
                "charge_type": "plan",
                "feature": {},
                "limit": {},
                "package_marks": ""
            },
        ]
        for pkg in pkg_list:
            Packages.from_dict(pkg).save()

    def init_admin_user(self):
        role = Role.objects.get(name="管理员")
        user = User(username="admin@knownsec.com", createAt=arrow.utcnow().datetime, roleIds=[role]).save()
        token_obj = Token(roleIds=[role], createBy=user.id).save()
        token = create_access_token(identity=token_obj.id, additional_claims={"entityType": "app"},
                                    expires_delta=datetime.timedelta(days=365 * 80))
        token_obj.token = token
        token_obj.save()
        return token

    def run(self):
        self.init_role()
        self.init_package()
        token = self.init_admin_user()
        print(f"初始化完成, 管理员token是 \n {token}", )
